package contrl

import (
	"core/env"
	"core/minio_client"
	"core/mysql"
	"core/utils"
	"db"
	"io"
	"net/http"
	"path/filepath"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/minio/minio-go"
)

type BasicControl struct{}

type LoginResponse struct {
	RealName  string
	Phone     string
	ImgDomain string
	Token     string
}

func (*BasicControl) Login(c *gin.Context) (res interface{}, e Error) {
	p := new(db.AdminPlayer)
	p.UserName = c.PostForm("username")
	if p.UserName == "" {
		return nil, GenErrorMsg("请输入用户名")
	}
	err := mysql.Load(p)
	if err != nil {
		return nil, GenError(err)
	}
	if p.Password != c.PostForm("password") {
		return nil, GenError(err)
	}
	res = LoginResponse{
		RealName:  p.RealName,
		Phone:     p.Phone,
		ImgDomain: env.Conf.ServerUrl,
		Token:     utils.Encrypt(Sign{Uid: p.ID, ExpiredAt: time.Now().Add(time.Hour * 24)}, env.Conf.AppSecret2),
	}
	return
}

func (*BasicControl) Logout(c *gin.Context) (res interface{}, e Error) {
	return
}

func (*BasicControl) UserInfo(c *gin.Context) (res interface{}, e Error) {
	sign := GetSign(c)
	utils.InfoJSON(sign)

	p := &db.AdminPlayer{ID: sign.Uid}
	err := mysql.Load(p)
	if err != nil {
		return nil, GenError(err)
	}
	res = LoginResponse{
		RealName:  p.RealName,
		Phone:     p.Phone,
		ImgDomain: env.Conf.ServerUrl,
	}
	return
}

func (*BasicControl) HelloWorld(c *gin.Context) (res interface{}, e Error) {
	res = "hello world"
	return
}

// 图片显示
func (*BasicControl) Image(c *gin.Context) {
	image := c.Param("image")
	var contentType string
	switch filepath.Ext(image) {
	case ".png":
		contentType = "image/png"
	case ".jpg", ".jpeg":
		contentType = "image/jpg"
	default:
		c.String(402, "图片格式不正确")
		return
	}

	object, err := minio_client.Client.GetObject(db.PicBucket, image, minio.GetObjectOptions{})
	if err != nil {
		c.String(402, err.Error())
		return
	}

	c.Status(http.StatusOK)
	c.Header("contentType", contentType)

	_, err = io.Copy(c.Writer, object)
	if err != nil {
		c.String(500, err.Error())
		return
	}
	return
}
